package com.hh.common.filter.login;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.hh.admin.common.bean.LoginUserInfo;
import com.hh.common.consts.AdminConst;

/**
 * 过滤器：后台URL用户校验
 * 
 * @author 冯昌硕
 * @create 2012-12-17 下午8:42:54
 */
public class AdminLoginFilter implements Filter {
    
    private static final Logger log = Logger.getLogger(AdminLoginFilter.class);

    @Override
    public void destroy() {
        log.info("后台用户登录过滤器销毁");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        //log.debug("用户后台登录判断过滤器调用方法 begin");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession();
        
        StringBuffer urlBui = request.getRequestURL();
        //log.debug("后台登录过滤器URL=[" + urlBui + "]");
        
        boolean needChkUrl = true;
        if(urlBui.toString().contains("/admin/index.jsp") 
                || urlBui.toString().contains("/admin/adminLogin.do")
                || urlBui.toString().contains("/admin/style")) {
            needChkUrl = false;
        }
        
        if(needChkUrl) {
            
            Object obj = session.getAttribute(AdminConst.SESSION_ATTR_USERINFO);
            if((obj == null) || !(obj instanceof LoginUserInfo)) {
                log.info("未登录后台就打开后台的连接[" + urlBui +  "]，返回到登录界面");
                HttpServletResponse response = (HttpServletResponse) res;
                response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
                return;
            }
            
        }
        
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        log.info("后台用户登录过滤器初始化");
    }

}
